<template>
	<div class="letter_list_wrapper" v-loading="loading">
		<div class="button">
			<el-form :inline="true" :model="listQuery" size="medium">
				<el-form-item><el-input v-model="listQuery.fromName" placeholder="发信人" clearable></el-input></el-form-item>
				<el-form-item>
					<el-select v-model="listQuery.status" placeholder="信件状态" clearable>
						<el-option label="私密" value="0"></el-option>
						<el-option label="公开" value="1"></el-option>
					</el-select>
				</el-form-item>
				<el-form-item><el-button type="primary" @click="getLetterListData">查询</el-button></el-form-item>
			</el-form>
			<el-button size="medium" type="danger" v-if="selectedLetter.length > 0" @click="handleBatchDeleteLetter">批量删除信件</el-button>
		</div>
		<div class="table">
			<el-table :data="letterListData" style="width: 100%" @selection-change="handleSelectionChange" row-key="id" :expand-row-keys="expandKeys" @expand-change="rowClick">
				<el-table-column type="expand" width="40">
					<template slot-scope="{ row }">
						<div class="letter_reply_list" v-for="(item, index) in row.props" :key="index">
							<div class="content">
								<font color="#f60">回复：</font>
								{{ item.content }}
							</div>
							<div class="button">
								<el-button type="text" size="medium" @click="replyDetail(item, row)">编辑</el-button>
								<el-button type="text" size="medium" @click="replyDelete(item, row)">删除</el-button>
							</div>
						</div>
					</template>
				</el-table-column>
				<el-table-column type="selection" width="42"></el-table-column>
				<el-table-column prop="fromName" label="发信人" min-width="300">
					<template slot-scope="{ row }">
						<template v-if="!row.fromName">
							<font color="#ccc">匿名人员</font>
						</template>
						<template v-else>
							{{ row.fromName }}
						</template>
					</template>
				</el-table-column>
				<el-table-column prop="createTime" label="发信时间" min-width="180"></el-table-column>
				<el-table-column prop="status" label="信件状态" min-width="120">
					<template slot-scope="{ row }">
						<el-tag type="success" v-if="row.status === '0'">私密</el-tag>
						<el-tag type="danger" v-else-if="row.status === '1'">公开</el-tag>
					</template>
				</el-table-column>
				<el-table-column label="操作" width="136">
					<template slot-scope="{ row }">
						<el-button-group>
							<el-button type="primary" size="small" @click="handleLookDetail(row)">查看</el-button>
							<el-button type="danger" size="small" @click="handleDeleteLetter(row.id)">删除</el-button>
						</el-button-group>
					</template>
				</el-table-column>
			</el-table>
		</div>
		<div class="page">
			<Pagination :total="dataCount" @change="getLetterListData" :page.sync="listQuery.page" :limit.sync="listQuery.limit" />
		</div>
		<el-dialog :visible.sync="detailDialog" width="992px" custom-class="letter_detail_wrapper">
			<template slot="title">
				<h2>{{ letterDetailData.fromName || '匿名人员' + '发来的信件：' }}</h2>
				<p>
					是否公开：
					<el-switch v-model="letterDetailData.status" @change="updateStatusRequest" active-value="1" inactive-value="0" active-color="#f56c6c"></el-switch>
				</p>
			</template>
			<div class="letter_detail_content" v-html="letterDetailData.content"></div>
			<template slot="footer">
				<el-button size="medium" @click="detailDialog = false">关闭</el-button>
				<el-button size="medium" type="primary" @click="handleUpdateLetterStatus" :loading="btnLoading">回复</el-button>
			</template>
		</el-dialog>
		<el-dialog :visible.sync="detailDialog2" width="992px" custom-class="letter_detail_wrapper">
			<template slot="title">
				<h2>回复：{{ letterDetailData.fromName || '匿名人员' }} 发来的信件：</h2>
			</template>
			<div class="letter_detail_reply">
				<h4>回复内容：</h4>
				<el-input type="textarea" :autosize="{ minRows: 4, maxRows: 8 }" v-model="reply.content" placeholder="请输入内容"></el-input>
			</div>
			<template slot="footer">
				<el-button size="medium" @click="detailDialog2 = false">关闭</el-button>
				<el-button size="medium" type="primary" @click="replyClick" :loading="btnLoading2">确定</el-button>
			</template>
		</el-dialog>
	</div>
</template>

<script>
import { mapActions } from 'vuex';
import { getSession } from '@/utils/session';
import { getLetterByLeader, updateLetterStatus, deteleMailLetter, batchDeleteLetter } from '@/api/admin/letter/index';
import { leadMailReplyAdd, leadMailReplyDelete, leadMailReplyQuery, leadMailReplyUpdate } from '@/api/admin/letter/leadMailReply';
export default {
	data() {
		return {
			loading: false,
			listQuery: {
				page: 1,
				limit: 10
			},
			dataCount: 0,
			letterListData: [],
			detailDialog: false,
			letterDetailData: {},
			btnLoading: false,
			selectedLetter: [],
			detailDialog2: false,
			btnLoading2: false,
			reply: {
				id: '',
				content: ''
			},
			leadMailId: '',
			expandKeys: [],
			userInfo: {}
		};
	},
	mounted() {
		this.getQueryTbUserList();
	},
	methods: {
		...mapActions(['queryTbUserById', 'getDictionaryEnumListVal']),
		//获取信件列表
		async getLetterListData() {
			let params = await this.formatRequestParams().then((res) => res);
			let result = await getLetterByLeader(params).then((res) => res.data);
			if (result.code === '0') {
				this.dataCount = parseInt(result.count);
				this.letterListData = !result.data ? [] : [...result.data];
			}
		},
		async getQueryTbUserList() {
			let userInfo = JSON.parse(getSession('userinfo'));
			userInfo = await this.queryTbUserById(userInfo.id);
			this.userInfo = userInfo.data[0];
			this.getLetterListData();
		},
		//格式化请求参数
		async formatRequestParams() {
			let params = { ...this.listQuery };
			if (this.userInfo.account !== 'admin') {
				if (this.userInfo.education && this.userInfo.education != '') {
					params['toPerson'] = this.userInfo.education;
				} else {
					params['toPerson'] = 'noleader';
				}
			}
			return params;
		},

		//查看信件详情
		handleLookDetail(row) {
			this.leadMailId = row.id;
			this.letterDetailData = { ...row };
			this.detailDialog = true;
		},

		//删除信件
		handleDeleteLetter(id) {
			let that = this;
			this.$confirm('此操作将永久删除该信件, 是否继续?', '提示', {
				confirmButtonText: '确定',
				cancelButtonText: '取消',
				type: 'warning',
				async beforeClose(action, instance, done) {
					if (action === 'confirm') {
						instance.confirmButtonLoading = true;
						await that.deleteLetterRequest(id);
						instance.confirmButtonLoading = false;
						done();
					} else {
						done();
					}
				}
			}).catch(() => {});
		},

		//删除请求
		async deleteLetterRequest(id) {
			let result = await deteleMailLetter(id).then((res) => res.data);
			if (result.code === '0') {
				this.$message.success('删除信件成功');
				this.getLetterListData();
			}
		},

		//批量删除信件
		handleBatchDeleteLetter() {
			let that = this;
			this.$confirm('此操作将永久删除选中信件, 是否继续?', '提示', {
				confirmButtonText: '确定',
				cancelButtonText: '取消',
				type: 'warning',
				async beforeClose(action, instance, done) {
					if (action === 'confirm') {
						let ids = that.selectedLetter.map((item) => item.id);
						instance.confirmButtonLoading = true;
						await that.batchDeleteRequest(ids);
						instance.confirmButtonLoading = false;
						done();
					} else {
						done();
					}
				}
			}).catch(() => {});
		},

		//批量删除信件请求
		async batchDeleteRequest(ids) {
			let result = await batchDeleteLetter(ids).then((res) => res.data);
			if (result.code === '0') {
				this.$message.success('信件批量删除成功');
				this.getLetterListData();
			}
		},

		//点击确定查看并公开信件
		handleUpdateLetterStatus() {
			// let currLetterId = this.letterDetailData.id;
			// let originalLetter = this.letterListData.find(item => item.id === currLetterId);
			// if (this.letterDetailData.status !== originalLetter.status) {
			// 	this.btnLoading = true;
			// 	this.updateStatusRequest();
			// } else {
			// 	this.detailDialog = false;
			// }
			this.detailDialog2 = true;
			this.btnLoading2 = false;
			this.reply = { id: '' };
		},
		async replyClick() {
			this.btnLoading2 = true;
			var params = { content: this.reply.content, leadMailId: this.leadMailId };
			let result;
			if (this.reply.id == '') {
				result = await leadMailReplyAdd(params).then((res) => res.data);
			} else {
				params.id = this.reply.id;
				result = await leadMailReplyUpdate(params).then((res) => res.data);
			}
			this.btnLoading2 = false;
			if (result.code === '0') {
				this.detailDialog = false;
				this.detailDialog2 = false;
				var _this = this;
				window.setTimeout(function () {
					_this.rowClick(_this.letterDetailData);
				}, 1000);
			}
		},

		//修改信件展示状态
		async updateStatusRequest() {
			let params = { ...this.letterDetailData };
			let result = await updateLetterStatus(params).then((res) => res.data);
			this.btnLoading = false;
			if (result.code === '0') {
				let currData = this.letterListData.find((item) => item.id === this.letterDetailData.id);
				currData.status = this.letterDetailData.status;
				// this.detailDialog = false;
				this.$message.success('修改信件状态成功');
			}
		},

		handleSelectionChange(selection) {
			this.selectedLetter = [...selection];
		},
		async rowClick(row) {
			var params = { leadMailId: row.id, limit: 99, page: 1 };
			let result = await leadMailReplyQuery(params).then((res) => res.data);
			row.props = result.data;
			this.expandKeys.shift();
			this.expandKeys.push(row.id);
		},
		//回复编辑
		replyDetail(replyItem, row) {
			this.letterDetailData = row;
			this.reply.content = replyItem.content;
			this.reply.id = replyItem.id;
			this.detailDialog2 = true;
			this.btnLoading2 = false;
		},
		replyDelete(replyItem, row) {
			var _this = this;
			this.$confirm('此操作将永久删除该回复, 是否继续?', '提示', {
				confirmButtonText: '确定',
				cancelButtonText: '取消',
				type: 'warning',
				async beforeClose(action, instance, done) {
					if (action === 'confirm') {
						let result = await leadMailReplyDelete(replyItem.id).then((res) => res.data);
						if (result.code === '0') {
							_this.rowClick(row);
							_this.$message.success('删除回复成功！');
						}
						done();
					} else {
						done();
					}
				}
			}).catch(() => {});
		}
	}
};
</script>

<style lang="scss" scoped>
.letter_list_wrapper {
	margin-top: 10px;
	.button {
		display: flex;
	}

	.el-form-item {
		margin: 0 10px 0 0;
	}
}
.letter_reply_list {
	display: flex;
	align-items: flex-start;
	justify-content: space-between;
	padding: 3px 0 3px 52px;
	.content {
		flex: 1;
		display: flex;
		align-items: flex-start;
		line-height: 28px;
		padding: 4px 0;
		font {
			flex-shrink: 0;
		}
	}
	.button {
		flex-shrink: 0;
		margin: 0 16px 0 36px;
	}
}
::v-deep .letter_detail_wrapper {
	min-width: 1000px;

	.el-dialog__header {
		display: flex;
		align-items: center;
		justify-content: space-between;
		padding: 10px 60px 10px 15px;
		border-bottom: solid 1px #ebeef5;

		h2 {
			font-size: 18px;
			font-weight: normal;
		}
	}

	.el-dialog__body {
		padding: 20px;
	}

	.el-dialog__footer {
		padding: 15px;
		border-top: solid 1px #ebeef5;
	}
}

.letter_detail_content {
	font-size: 16px;
	line-height: 2;
	color: #666;
}
</style>
